<template>
  <div class="manage-container">
    <el-card class="manage-card">
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <div class="button-group">
            <el-button type="primary" @click="handleAdd">添加商品</el-button>
            <el-button type="warning" @click="goToStatistics">统计数据</el-button>
          </div>
        </div>
      </template>

      <el-table :data="products" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column label="商品图片" width="120">
          <template #default="scope">
            <el-image
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                class="product-image"
                :preview-teleported="true"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品名称"/>
        <el-table-column prop="description" label="商品描述" show-overflow-tooltip/>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量" width="100">
          <template #default="scope">
            {{ scope.row.salesVolume }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'">
              {{ scope.row.status ? '已上架' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
                :type="scope.row.status ? 'warning' : 'success'"
                size="small"
                @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status ? '下架' : '上架' }}
            </el-button>
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />

      <!-- 添加编辑对话框 -->
      <el-dialog
          :title="editForm.id ? '编辑商品' : '添加商品'"
          v-model="dialogVisible"
          width="50%"
      >
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="商品名称">
            <el-input v-model="editForm.title"/>
          </el-form-item>

          <el-form-item label="商品描述">
            <el-input
                v-model="editForm.description"
                type="textarea"
                rows="3"
            />
          </el-form-item>
          <el-form-item label="商品链接">
            <el-input v-model="editForm.url"/>
          </el-form-item>

          <el-form-item label="商品价格">
            <el-input-number
                v-model="editForm.price"
                :min="0"
                :precision="2"
            />
          </el-form-item>

          <el-form-item label="商品分类">
            <el-select v-model="editForm.categoryId">
              <el-option label="技术/极客" :value="1"/>
              <el-option label="家居生活" :value="2"/>
              <el-option label="创意礼物" :value="3"/>
              <el-option label="玩具/游戏" :value="4"/>
              <el-option label="奢华物品" :value="5"/>
              <el-option label="奇葩搞怪" :value="6"/>
            </el-select>
          </el-form-item>

          <el-form-item label="目标人群">
            <el-select v-model="editForm.targetAudienceId">
              <el-option label="家人" :value="1"/>
              <el-option label="朋友" :value="2"/>
              <el-option label="同事" :value="3"/>
            </el-select>
          </el-form-item>


          <el-form-item label="商品图片">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="handleImageUpload"
            >
              <img v-if="editForm.image" :src="editForm.image" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-form-item label="产品特点 使用,进行分割">
          <el-input v-model="editForm.productFeatures" type="textarea" />
        </el-form-item>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {updateProductApi, updateStatusApi, addProductApi, adminGetProductApi, uploadImageApi} from '@/api/ProductApi'
import router from "@/router";

const products = ref([])
const dialogVisible = ref(false)
const editForm = reactive({
  id: '',
  title: '',
  description: '',
  url: '',
  price: 0,
  categoryId: 1,
  targetAudienceId: 1,
  image: '',
  productFeatures:"",
  status: 1
})

onMounted(() => {
  loadProducts()
})
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

const loadProducts = () => {
  adminGetProductApi(currentPage.value, pageSize.value).then(res => {
    if (res.data.code === 1) {
      products.value = res.data.data.records;
      total.value = res.data.data.total; // 假设返回的总记录数在 res.data.data.total 中
    } else {
      ElMessage.error('获取商品列表失败');
    }
  });
};

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  loadProducts();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadProducts();
};



const handleStatusChange = async (row) => {
  // 先更新本地状态
  const newStatus = !row.status;
  const updatedRow = {...row, status: newStatus};

  // 更新视图中的数据
  const index = products.value.findIndex(p => p.id === row.id);
  if (index !== -1) {
    products.value.splice(index, 1, updatedRow);
  }
  // 假设 updateStatusApi 返回一个 Promise
  // 将status转换成数字

  updateStatusApi(row.id, newStatus).then(
      res => {
        if (res.data.code == 1) {
          ElMessage.success(`商品已${newStatus ? '上架' : '下架'}`);
        } else {
          // 如果API调用失败，回滚本地状态更改
          const rollbackRow = {...updatedRow, status: !newStatus};
          if (index !== -1) {
            products.value.splice(index, 1, rollbackRow);
          }
          ElMessage.error('操作失败');
        }
      }
  )


}


const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(editForm, row)
}

const handleAdd = () => {
  dialogVisible.value = true
  Object.assign(editForm, {
    id: '',
    title: '',
    description: '',
    url: '',
    price: 0,
    type: 1,
    targetGroup: 1,
    image: '',
    productFeatures:"",
    status: true
  })
}

const handleImageUpload = (rawFile) => {
  if (!rawFile) { // 检查文件是否为空
    ElMessage.error('请选择一个有效的文件');
    return false;
  }

  const formData = new FormData();
  formData.append('file', rawFile); // 将文件添加到 FormData 对象中

  uploadImageApi(formData).then(res => {
    if (res.data.code === 1) {
      editForm.image = res.data.data; // 假设返回的 URL 在 res.data.data.url 中
    } else {
      ElMessage.error('图片上传失败');
    }
  })

  return false; // 阻止默认的上传行为
}


const handleSave = async () => {
  try {
    if (editForm.id) {
      updateProductApi(editForm).then(res => {
        if (res.data.code == 1) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          loadProducts()
        } else {
          ElMessage.error('保存失败')
        }
      })
    } else {
      addProductApi(editForm).then(res => {
        if (res.data.code == 1) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          loadProducts()
        } else {
          ElMessage.error('添加失败')
        }
      })
    }

  } catch (error) {
    ElMessage.error('操作失败')
  }
}
const goToStatistics = () => {
  router.push({name: 'StatisticsView'}) // 使用命名路由进行跳转
}

</script>

<style scoped>
.manage-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.manage-card {
  margin: 0 auto;
  max-width: 1200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.el-icon {
  font-size: 28px;
  color: #8c939d;
}
</style> 